package cn.myzf.ftp.cogradient.netty.handlers;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import cn.myzf.ftp.cogradient.netty.clientplugins.CosClient;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedStream;
import io.netty.util.CharsetUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static org.apache.coyote.http11.Constants.CONNECTION;

/**
 * @package cn.myzf.ftp.download.netty
 * @Date Created in 2019/12/29 16:26
 * @Author myzf
 */
public class QcloudServerHandler extends SimpleChannelInboundHandler<Object> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {


        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            //检测解码情况
            if (!request.decoderResult().isSuccess()) {
                sendError(ctx, BAD_REQUEST);
                return;
            }
            this.handlerReq(ctx, request);
        }
    }


    private void handlerReq(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        COSClient cosClient = CosClient.getCosClient();
        String bucketName = "";//你的bucketName
        if(StringUtils.isEmpty(bucketName)){
            throw new IllegalArgumentException("腾讯对象存储bucketName不能为空");
        }
        String key = "";//文件名
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        COSObject cosObject = cosClient.getObject(getObjectRequest);
        COSObjectInputStream cosObjectInput = cosObject.getObjectContent();
        long fileSize = cosObject.getObjectMetadata().getContentLength();
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        HttpUtil.setContentLength(response, fileSize);
        response.headers().set(CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // 设定默认文件输出名
        String fileName = URLUtil.encode(FileUtil.getName(cosObject.getKey()));
        response.headers().add("Content-disposition", "attachment; filename=" + fileName);
        if (HttpUtil.isKeepAlive(request)) {
            response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        ctx.write(response);
        ctx.write(new HttpChunkedInput(new ChunkedStream(cosObjectInput)), ctx.newProgressivePromise());
        ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (!HttpUtil.isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }


    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
